from django.http import JsonResponse
from django.views import View
from django.contrib.auth import login
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection

from meiduomall import settings
from apps.oauth.models import OAuthQQUser
from apps.users.models import User

import json
import re

# Create your views here.
"""
生成用户绑定连接
前端：点击qq登陆 前端发送一个axios请求
后端：
    接受请求
    业务上 
    满足qqOauth的要求，要拼接连接{code,url}
    url get qq/authorization
"""
class QQLoginView(View):

    def get(self,request):
        qq = OAuthQQ(
            client_id = settings.QQ_CLIENT_ID,
            client_secret = settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state = 'xxxxx'
        )

        qq_login_url = qq.get_qq_url()

        return JsonResponse({'code':0,'errmsg':'ok','login_url':qq_login_url})

"""
get
通过前端获取code
使用code向Oauth得到token
使用token换取唯一的openid
根据openid是否判断是否绑定过用户
绑定过：登陆
未绑定：重新绑定
"""
"""
post
前端：重定向到绑定用户的url，用户输入数据，前端发送一个axios请求
后端：
1.获取前端发送的数据，包含：手机号，密码，SMS-code，openid
2.数据判断 数据是否完整，数据格式判断正则表达式
3.判断手机号是否绑定用户
    已绑定：密码正确，直接将openid绑定用户并返回数据
    未绑定：新建用户绑定手机号
4.返回响应
"""
class OauthQQView(View):
    def get(self,request):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({"code":400,"errmsg":'error'})

        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state='xxxxx'
        )
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            response = JsonResponse({'code':300,'access_token':openid})
            return response
        else:
            login(request,qquser.user)
            response = JsonResponse({'code':0,'errmsg':'ok'})

            response.set_cookie('username',qquser.user.username)

            return response

    def post(self,request):

        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code_client = data_dict.get('sms_code')
        openid = data_dict.get('access_token')

        if not all([mobile,password,sms_code_client]):
            return JsonResponse({'code':400,'errmsg':'数据缺失'})

        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return JsonResponse({'code':400,'errmsg':'请输入正确的手机号'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$',password):
            return JsonResponse({'code':400,'serrmsg':'密码过于简单'})

        redis_conn = get_redis_connection('code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)

        if sms_code_server is None:
            return JsonResponse({'code':400,'errmsg':'验证码失效'})
        if sms_code_client == sms_code_server.decode():
            return JsonResponse({'code':400,'errmsg':'输入验证码错误'})

        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 手机号不存在用户
            user = User.objects.create_user(username=mobile,mobile=mobile,password=password)
        else:
            # 手机号已经存在用户 判断密码是否正确
            if not user.check_password(password):
                return JsonResponse({'code':400,'errmsg':'密码错误'})

        OAuthQQUser.objects.create(user=user,openid=openid)

        login(request,user)

        response = JsonResponse({'code':0,'errmsg':'ok'})

        response.set_cookie('username',user.username)

        return response





